#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2023-09-14 12:57
# @Author : hard work
# @File    : avg_jitter_util.py
# @Description :
import matplotlib.pyplot as plt
import pyshark
from numpy import *
import os


pcap_file = r"D:\Tools\3.pcap"


def get_pkt_rec_time(pcap_file, pkt_cnt):
    print(os.path.isfile(pcap_file))
    capture = pyshark.FileCapture(pcap_file, keep_packets=True)
    ticks_times = []
    count = 0
    for i, packet in enumerate(capture):
        rec_pkt_time = str(packet.frame_info.time_epoch)
        tmp = rec_pkt_time.split(".")[0][-1:]
        tmp1 = rec_pkt_time.split(".")[1]
        tmp = int(tmp + tmp1)
        if count == pkt_cnt:
            break
        ticks_times.append(tmp)
        count += 1
    print(count)
    return ticks_times, count


def sum_per_5_index(lst):
    avglst = []
    n = len(lst)
    print(n)
    for i in range(n):
        for j in range(0, n - i - 1):
            avgs = (lst[j + 1] - lst[j]) / 100000
            avglst.append(avgs)
    return avglst


def per_100_avg(lst, cnt):
    MAC_NUM = 100
    LST_INDEX = 0
    PORT_NUM = 1
    avg_lst = []
    while PORT_NUM <= cnt / MAC_NUM:
        ticks = lst[LST_INDEX * MAC_NUM: MAC_NUM * PORT_NUM]
        sums = (round(sum(ticks) / len(ticks), 5))
        avg_lst.append(sums)
        LST_INDEX += 1
        PORT_NUM += 1
    return avg_lst


if __name__ == '__main__':
    pkt_cnt = 5000
    grounp_cnt = 100
    x = []
    for i in range(1, pkt_cnt + 1):
        if i % 100 == 0:
            x.append(i)
    res, cnt = get_pkt_rec_time(pcap_file, pkt_cnt)
    m1 = sum_per_5_index(res)
    y = per_100_avg(m1, cnt)
    # 创建线图
    plt.plot(x, y)
    # 显示图形
    plt.show()
